import { TextEncoder } from '../../../transcoding/encoding'; 
const gbk = require('../../../transcoding/GbkTextEncoder.js');

const app = getApp()

const startLocationData=new Object()
const endLocationData=new Object()
const sendLocationData=new Object()
const sendAngleData=new Object()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    receiverText: '',
    receiverLength: 0,
    sendText: '',
    sendLength: 0,
    time: 1000,
    timeSend: false,
    startLocationData:'',
    endtLocationData:'',
    sendAngleData:'',
    x: 0,
    y: 0,
    hidden: true,
    defaultMotor:'../../../images/motoroff.png',
    extraClasses: ''
  },
  /**
   * 自定义数据
   */
  customData: {
    sendText: '',
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    canWrite: false,
    canRead: false,
    canNotify: false,
    canIndicate: false,
    time: 0,
    setLocationFlag: false,
    sendLocationData:'',
    state:false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    const self = this
    this.customData.deviceId = options.deviceId
    this.customData.serviceId = options.serviceId
    this.customData.characteristicId = options.characteristicId
    this.customData.canWrite = options.write === 'true' ? true : false
    this.customData.canRead = options.read === 'true' ? true : false
    this.customData.canNotify = options.notify === 'true' ? true : false
    this.customData.canIndicate = options.indicate === 'true' ? true : false
    console.log("com write is  "+options.write)
    console.log("com read is  "+options.read)
    console.log("com notify is  "+options.notify)
    console.log("com indicate is  "+options.indicate)
    const ctx = wx.createCanvasContext('myCanvas')
    ctx.drawImage('../../../images/logo.png', -30, -10, 380, 250)
    ctx.draw()
   /**
     * 如果支持notify
     */

    const is02Module = options.serviceId == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
    var characteristicId = ""
    if(is02Module){
       characteristicId =  '49535343-1E4D-4BD9-BA61-23C647249616'
    }else{
      characteristicId = options.characteristicId
    }

   if (options.notify || is02Module) {
     console.log("com characteristicId is "+options.characteristicId)
     wx.notifyBLECharacteristicValueChange({
       deviceId: options.deviceId,
       serviceId: options.serviceId,
       characteristicId,
       state: true,
       success: function(res) {
         // do something...
         console.log("com is start notify !!!")
       },
       fail:function(res){
         console.log("com start notify is fail !!!")
       }
     })
   }
 },
 /**
  * 生命周期函数--监听页面初次渲染完成
  */
 onReady: function () {
   const self = this;

   function buf2string(buffer) {
     var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
     return arr.map((char, i) => {
       return String.fromCharCode(char);
     }).join('');
   }

   function myHextoString(hex) {
     let out = '';

     for (let i = 0; i < hex.length; i++) {
       let h = (hex[i] / 16);
       console.log("hex i is "+hex[i]);
       if (h >= 10) {
         h = h - 10 + 65;
       } else {
         h = h + 48;
       }
       h = String.fromCharCode(h);
       out += h;
   
       let l = hex[i] % 16;
       if (l >= 10) {
         l = l - 10 + 65;
       } else {
         l = l + 48;
       }
       l = String.fromCharCode(l);
       out += l+" ";
   
     }
     return out
   }

   /** 
    * 监听蓝牙设备的特征值变化
    */
   wx.onBLECharacteristicValueChange(function (res) {
     
     const receiverText = buf2string(res.value);

     console.log("receiveHex is "+self.data.receiveHex);
     var message;
     if(!self.data.receiveHex){
       const buffer = new Uint8Array(res.value);
       message = gbk.decode(buffer);
     }else{
       message = myHextoString(new Uint8Array(res.value));
     }
     
     console.log("message lenght is "+message.length);
     
     for(var i = 0;i<message.byteLength;i++){
       console.log("message is "+message[i])
     }

     self.setData({
       receiverLength: self.data.receiverLength + receiverText.length,
     })
     setTimeout(() => {
       self.setData({
         receiverText: (self.data.receiverText + message).substr(-4000, 4000),
       })
     }, 200)
   })
 },
 /**
  * 生命周期函数--监听页面卸载
  */
 onUnload: function () {
   clearInterval(this.customData.time)
   this.setData({
     receiverText: '',
     receiverLength: 0,
     sendText: '',
     sendLength: 0,
     time: 1000,
     timeSend: false
   })
 },




 /**
  * 更新发送框内容
  */
 updateSendText: function(event) {
   const value = event.detail.value
   this.customData.sendText = value
   this.setData({
     sendText: value
   })
 },
 /**
  * 更新定时发送时间间隔
  */
 updateTime: function(event) {
   const self = this
   const value = event.detail.value
   this.setData({
     time: /^[1-9]+.?[0-9]*$/.test(value) ? +value : 1000
   })
   clearInterval(this.customData.time)
   const deviceId = this.customData.deviceId // 设备ID
   const serviceId = this.customData.serviceId // 服务ID
   const characteristicId = this.customData.characteristicId // 特征值ID
   this.customData.time = setInterval(() => {
     const sendText = self.customData.sendText
     const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
     if (app.globalData.connectState) {
       if (self.customData.canWrite) { // 可写
         self.writeData({ deviceId, serviceId, characteristicId, sendPackage })
       }
     }
   }, self.data.time)
 },
 /**
  * 清除接收
  */
 clearReceiverText: function(event) {
   // this.customData.receiverText = ''
   this.setData({
     receiverText: '',
     receiverLength: 0,
     sendLength: 0
   })
 },

 /*
 *复选按钮
 */ 
 checkboxChange:function(e){
   var send = false;
   var receive = false;

   if(e.detail.value == "send-hex" ){
     send = true
   } else if(e.detail.value == "receive-hex"){
     receive = true
   }else if(e.detail.value == ""){
     console.log("不选")
   }else{
     send = true;
     receive = true;
   }

   this.setData({
     sendHex:send,
     receiveHex:receive,
   })

 },

 /**
  * 清除发送
  */
 clearSendText: function(event) {
   this.customData.sendText = ''
   this.setData({
     sendText: '',
     sendLength: 0
   })
 },


 myStringtoHex: function (str) {
   str = str.toLowerCase();
   console.log("str length is "+str.length);
   let newBuffer = new ArrayBuffer(str.length / 2);
   let hexBuffer = new Uint8Array(newBuffer, 0);
   let h = 0,
     l = 0;
   for (let i = 0; i < str.length / 2; i++) {
     h = str.charCodeAt(2 * i);
 
     l = str.charCodeAt(2 * i + 1);
     if (48 <= h && h <= 57) {
       h = h - 48;
     } else {
       h = h - 97 + 10;
     }
     if (48 <= l && l <= 57) {
       l = l - 48;
     } else {
       l = l - 97 + 10;
     }
     hexBuffer[i] = h * 16 + l;
   }
   return hexBuffer;
 },

 arrayToUint8Array:function (buff){
   const str = String.fromCharCode.apply(null, new Uint8Array(buff));
   var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
   var bufView = new Uint8Array(buf);
   for (var i = 0, strLen = str.length; i < strLen; i++) {
     bufView[i] = str.charCodeAt(i);
     console.log("bufView is "+bufView[i]);
   }
   return buf;
 },

 reSetLocation: function(event) {
   this.setData({
    startLocationData: '',
    endLocationData: '',
    sendLocationData: ''
  })
 },
 setStartLocation: function(event) {
  if (startLocationData) {
    this.setData({
      startLocationData: JSON.stringify(startLocationData)
    })
    this.setLocationFlag = true;
  } else {
    this.setLocationFlag = false;
  }
 },
 setEndLocation: function(event) {
  if (endLocationData) {
    this.setData({
      endLocationData: JSON.stringify(endLocationData)
    })
  }
 },
 sendLocation: function(event) {
  this.sendLocationData = JSON.stringify(sendLocationData)
  this.sentMsg2ArduinoBluetooth(this.sendLocationData);
  console.log(this.sendLocationData);
 },

 slider4S1change: function(event) {
   const location = event.detail.value;
   if (this.setLocationFlag) {
    //存入最后位置
    endLocationData["s1end"] = location;
    sendLocationData["s1end"] = location;
   } else {
     //存入初始位置
     startLocationData["s1start"]= location;
     sendLocationData["s1start"] = location;
    }
   const str = "s1"+location;
   this.sentMsg2ArduinoBluetooth(str)
 },
  slider4S2change: function(event) {
    const location = event.detail.value;
   if (this.setLocationFlag) {
     //存入最后位置
     endLocationData["s2end"] = location;
     sendLocationData["s2end"] = location;
   } else {
     //存入初始位置
     startLocationData["s2start"] = location;
     sendLocationData["s2start"] = location;
   }
    const str = "s2"+location;
    this.sentMsg2ArduinoBluetooth(str)
  },
  slider4S3change: function(event) {
    const location = event.detail.value;
    if (this.setLocationFlag) {
      //存入最后位置
      endLocationData["s3end"] = location;
      sendLocationData["s3end"] = location;
    } else {
      //存入初始位置
      startLocationData["s3start"] = location;
      sendLocationData["s3start"] = location;
    }
    const str = "s3"+location;
     this.sentMsg2ArduinoBluetooth(str)
  },
  slider4S4change: function(event) {
    const location = event.detail.value;
    if (this.setLocationFlag) {
      //存入最后位置
      endLocationData["s4end"] = location;
      sendLocationData["s4end"] = location;
    } else {
      //存入初始位置
      startLocationData["s4start"] = location;
      sendLocationData["s4start"] = location;
    }
    const str = "s4"+location;
     this.sentMsg2ArduinoBluetooth(str)
  },

 sentMsg2ArduinoBluetooth:function(v){
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    
    const sendText = v
    let buff;
    if(this.data.sendHex){
      const un = this.myStringtoHex(sendText)
      buff = this.arrayToUint8Array(un);
    }else{
      buff = this.gbkToArray(sendText);
    }

    const sendPackage = app.getSendPackage(buff) // 数据分每20个字节一个数据包数组
    console.log("connectState is "+app.globalData.connectState+"  canWrite is "+this.customData.canWrite);
    //console.log("sendPack length is "+sendPackage.length+"  The sendPackage one is "+sendPackage[0]);
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        this.writeData( deviceId, serviceId, characteristicId, sendPackage )
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
 },


 /**
  * 手动发送
  */
 manualSend: function(event) {
   const deviceId = this.customData.deviceId // 设备ID
   const serviceId = this.customData.serviceId // 服务ID
   const characteristicId = this.customData.characteristicId // 特征值ID
   
   const sendText = this.customData.sendText
   let buff;
   if(this.data.sendHex){
     const un = this.myStringtoHex(sendText)
     buff = this.arrayToUint8Array(un);
   }else{
     buff = this.gbkToArray(sendText);
   }

   const sendPackage = app.getSendPackage(buff) // 数据分每20个字节一个数据包数组
   console.log("connectState is "+app.globalData.connectState+"  canWrite is "+this.customData.canWrite);
   //console.log("sendPack length is "+sendPackage.length+"  The sendPackage one is "+sendPackage[0]);
   if (app.globalData.connectState) {
     if (this.customData.canWrite) { // 可写
       this.writeData( deviceId, serviceId, characteristicId, sendPackage )
     }
   } else {
     wx.showToast({
       title: '已断开连接',
       icon: 'none'
     })
   }
 },
 /**
  * 自动发送
  */
 timeChange (event) {
   this.setData({
     timeSend: event.detail.value.length ? true : false
   })
   if (!this.data.timeSend) {
     clearInterval(this.customData.time)
   } else {
     const self = this
     const deviceId = this.customData.deviceId // 设备ID
     const serviceId = this.customData.serviceId // 服务ID
     const characteristicId = this.customData.characteristicId // 特征值ID
     this.customData.time = setInterval(() => {
       const sendText = self.customData.sendText

       let buff;
       if(this.data.sendHex){
         const un = this.myStringtoHex(sendText)
         buff = this.arrayToUint8Array(un);
       }else{
         buff = this.gbkToArray(sendText);
       }
       const sendPackage = app.getSendPackage(buff) // 数据分每20个字节一个数据包数组
       if (app.globalData.connectState) {
         if (self.customData.canWrite) { // 可写
           self.writeData( deviceId, serviceId, characteristicId, sendPackage )
         }
       }
     }, self.data.time)
   }
 },

 //转码
 gbkToArray(content){
   var _encoder = new TextEncoder("gb2312", {NONSTANDARD_allowLegacyEncoding: true});
   // content 需要打印的字符串
   const val = _encoder.encode(content);
   //console.log("gbkToArryval",val);
   return  val.buffer;
 },
 /**
  * 向特征值写数据(write)
  */
 writeData: function (deviceId, serviceId, characteristicId, sendPackage, index = 0) {
   const self = this
   let i = index;
   if(sendPackage == null )
     return;
   let len = sendPackage.length;

   function buf2string(buffer) {
     var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
     return arr.map((char, i) => {
       return String.fromCharCode(char);
     }).join('');
   }

   if (len && len > i) {
     wx.writeBLECharacteristicValue({
       deviceId,
       serviceId,
       characteristicId,
       value: sendPackage[i],
       success: function (res) {
         self.setData({
           sendLength: self.data.sendLength + sendPackage[i].byteLength // 更新已发送字节数
         })
         i += 1;
         self.writeData(deviceId, serviceId, characteristicId, sendPackage, i) // 发送成功，发送下一个数据包
       },
       fail: function (res) {
         console.log("发送失败: "+buf2string(res.value));
         console.log("res.value length is "+new Uint8Array(res.value).length);
         self.writeData(deviceId, serviceId, characteristicId, sendPackage, index) // 发送失败，重新发送
       }
     })
   }
 },
 triggerTransition: function () {
  if (this.data.extraClasses == 'box-transition box-moved') {
    this.setData({
      extraClasses: 'box-transition'
    })
  } else {
    this.setData({
      extraClasses: 'box-transition box-moved'
    })
  }
},
triggerAnimation: function () {
  this.setData({
    extraClasses: 'box-animation'
  })
  
},
transitionEnd: function () {
  console.log('渐变已结束')
  this.setData({
    extraClasses: ''
  })
},
animationStart: function () {
  console.log('动画已开始')
},
animationIteration: function () {
  console.log('动画进行中')
},
start (e) {
  this.setData({
    hidden: false,
    x: e.touches[0].x,
    y: e.touches[0].y
  })
},
move (e) {
  this.setData({
    x: e.touches[0].x,
    y: e.touches[0].y
  })
  sendAngleData['x']=parseInt(e.touches[0].x)
  sendAngleData['y']=parseInt(e.touches[0].y)
  this.sendLocationData = JSON.stringify(sendAngleData)
  this.sentMsg2ArduinoBluetooth(this.sendLocationData+"%");
  console.log(this.sendLocationData);
},
end (e) {
  this.setData({
    hidden: true
  })
},
sendAngle:function(x,y){
  console.log('x-->'+x)
  console.log('y-->'+y)
  sendAngleData['x']=x
  sendAngleData['y']=y
  this.sentMsg2ArduinoBluetooth(str)
},

setMotor:function(){
  var  status = this.customData.state
  console.log(status)
  var motorOn = '../../../images/motoron.png'
  var motorOff = '../../../images/motoroff.png'
  if (!status) {
    this.setData({
      defaultMotor:motorOn,
    })
    this.sentMsg2ArduinoBluetooth("str")
  }else{
    this.setData({
      defaultMotor:motorOff,
    })
  }
  this.customData.state = !status
},
sendBullet:function(){
  var  status = this.customData.state
  if (status) {
    this.triggerTransition()
  wx.vibrateShort()
  } else {
    wx.showToast({
      title: '请开启飞轮',
      icon: 'none'
    })
  }
},
})